package com.example.excel_db.controller;

import com.example.excel_db.dto.ApiResponse;
import com.example.excel_db.dto.ExcelImportTaskDTO;
import com.example.excel_db.service.ExcelImportExportService;
import com.example.excel_db.service.ExcelTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * Excel导入导出控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/excel")
@RequiredArgsConstructor
public class ExcelImportExportController {

    private final ExcelImportExportService importExportService;
    private final ExcelTemplateService templateService;

    /**
     * 导入Excel数据
     */
    @PostMapping("/import/{templateId}")
    public ApiResponse<ExcelImportTaskDTO> importExcel(
            @PathVariable Long templateId,
            @RequestParam("file") MultipartFile file) {
        try {
            ExcelImportTaskDTO result = importExportService.importExcel(templateId, file);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("导入Excel数据失败: templateId={}", templateId, e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 导出Excel数据
     */
    @PostMapping("/export/{templateId}")
    public ResponseEntity<byte[]> exportExcel(
            @PathVariable Long templateId,
            @RequestBody List<Map<String, Object>> dataList) {
        try {
            byte[] fileContent = importExportService.exportExcel(templateId, dataList);
            String fileName = templateService.getTemplateById(templateId).getName() + "_export.xlsx";
            
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .body(fileContent);
        } catch (Exception e) {
            log.error("导出Excel数据失败: templateId={}", templateId, e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取导入任务状态
     */
    @GetMapping("/import/tasks/{taskId}")
    public ApiResponse<ExcelImportTaskDTO> getImportTaskStatus(@PathVariable Long taskId) {
        try {
            ExcelImportTaskDTO result = importExportService.getImportTaskStatus(taskId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取导入任务状态失败: taskId={}", taskId, e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 取消导入任务
     */
    @PostMapping("/import/tasks/{taskId}/cancel")
    public ApiResponse<Boolean> cancelImportTask(@PathVariable Long taskId) {
        try {
            boolean result = importExportService.cancelImportTask(taskId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("取消导入任务失败: taskId={}", taskId, e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 重试失败的导入任务
     */
    @PostMapping("/import/tasks/{taskId}/retry")
    public ApiResponse<ExcelImportTaskDTO> retryImportTask(@PathVariable Long taskId) {
        try {
            ExcelImportTaskDTO result = importExportService.retryImportTask(taskId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("重试导入任务失败: taskId={}", taskId, e);
            return ApiResponse.error(e.getMessage());
        }
    }
}